package com.amt.olcacon;

import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.io.*;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Pattern;

public class CompleteWordTemplateProcessor {
    
    public static void main(String[] args) throws Exception {
        // 加载模板文件
        InputStream is = new FileInputStream("src/main/resources/templates/LCA报告模板.docx");
        XWPFDocument doc = new XWPFDocument(is);
        
        // 1. 先替换所有文本占位符
        replaceTextPlaceholders(doc);
        
        // 2. 替换表格占位符
        replaceTablePlaceholders(doc);
        
        // 保存修改后的文档
        FileOutputStream out = new FileOutputStream("src/main/resources/templates/LCA报告_完成.docx");
        doc.write(out);
        out.close();
        doc.close();
        
        System.out.println("文档处理完成！");
    }
    
    /**
     * 替换文本占位符
     */
    public static void replaceTextPlaceholders(XWPFDocument doc) {
        // 替换段落中的占位符
        for (XWPFParagraph paragraph : doc.getParagraphs()) {
            replaceTextInParagraph(paragraph);
        }
        
        // 替换表格中的占位符
        for (XWPFTable table : doc.getTables()) {
            for (XWPFTableRow row : table.getRows()) {
                for (XWPFTableCell cell : row.getTableCells()) {
                    for (XWPFParagraph para : cell.getParagraphs()) {
                        replaceTextInParagraph(para);
                    }
                }
            }
        }
    }
    
    /**
     * 在段落中替换文本占位符
     */
    private static void replaceTextInParagraph(XWPFParagraph paragraph) {
        String text = paragraph.getText();
        if (text == null) return;
        
        // 定义占位符映射
        java.util.Map<String, String> placeholderMap = new java.util.HashMap<>();
        placeholderMap.put("\\$\\{productName\\}", "太阳能光伏组件");
        placeholderMap.put("\\$\\{specification\\}", "540W单晶硅");
        placeholderMap.put("\\$\\{modelNo\\}", "PV-540S");
        placeholderMap.put("\\$\\{productUnitName\\}", "1kW·h发电量");
        placeholderMap.put("\\$\\{boundary\\}", "从摇篮到大门（从原料开采到产品出厂）");
        placeholderMap.put("\\$\\{bondaryPicture\\}", "[系统边界图]");
        
        // 替换占位符
        for (java.util.Map.Entry<String, String> entry : placeholderMap.entrySet()) {
            if (text.contains(entry.getKey().replace("\\", ""))) {
                replaceTextInRuns(paragraph, entry.getKey().replace("\\", ""), entry.getValue());
            }
        }
    }
    
    /**
     * 替换运行中的文本
     */
    private static void replaceTextInRuns(XWPFParagraph paragraph, String placeholder, String replacement) {
        try {
            String paragraphText = paragraph.getText();
            if (paragraphText == null || !paragraphText.contains(placeholder)) {
                return;
            }
            
            // 查找包含占位符的运行
            for (XWPFRun run : paragraph.getRuns()) {
                String runText = run.getText(0);
                if (runText != null && runText.contains(placeholder)) {
                    runText = runText.replace(placeholder, replacement);
                    run.setText(runText, 0);
                    System.out.println("替换占位符: " + placeholder + " -> " + replacement);
                }
            }
        } catch (Exception e) {
            System.err.println("替换文本时出错: " + e.getMessage());
        }
    }
    
    /**
     * 替换表格占位符
     */
    public static void replaceTablePlaceholders(XWPFDocument doc) {
        boolean found = false;
        
        for (XWPFTable table : doc.getTables()) {
            if (containsTablePlaceholder(table)) {
                System.out.println("找到表格占位符，开始替换...");
                replaceAllocationTable(table);
                found = true;
                break;
            }
        }
        
        if (!found) {
            System.out.println("警告：未找到表格占位符 {{ALLOCATION_TABLE}}");
            // 列出所有表格内容帮助调试
            listAllTablesContent(doc);
        }
    }
    
    /**
     * 检查表格是否包含占位符
     */
    private static boolean containsTablePlaceholder(XWPFTable table) {
        for (XWPFTableRow row : table.getRows()) {
            for (XWPFTableCell cell : row.getTableCells()) {
                String cellText = getCellText(cell).trim();
                if (cellText.contains("{{ALLOCATION_TABLE}}")) {
                    System.out.println("找到占位符表格，单元格内容: " + cellText);
                    return true;
                }
            }
        }
        return false;
    }
    
    /**
     * 获取单元格完整文本
     */
    private static String getCellText(XWPFTableCell cell) {
        StringBuilder text = new StringBuilder();
        for (XWPFParagraph para : cell.getParagraphs()) {
            text.append(para.getText());
        }
        return text.toString();
    }
    
    /**
     * 替换分配表格
     */
    private static void replaceAllocationTable(XWPFTable table) {
        try {
            // 清空表格内容
            clearTableContent(table);
            
            // 设置表格样式
            setupTableStyle(table);
            
            // 创建表头
            createTableHeader(table);
            
            // 生成并填充数据
            List<AllocationData> dataList = generateAllocationData();
            createDataRows(table, dataList);
            
            System.out.println("表格替换完成，共插入 " + dataList.size() + " 行数据");
            
        } catch (Exception e) {
            System.err.println("替换表格时出错: " + e.getMessage());
            e.printStackTrace();
        }
    }
    
    /**
     * 清空表格内容
     */
    private static void clearTableContent(XWPFTable table) {
        int rowCount = table.getNumberOfRows();
        for (int i = rowCount - 1; i >= 0; i--) {
            table.removeRow(i);
        }
    }
    
    /**
     * 设置表格样式
     */
    private static void setupTableStyle(XWPFTable table) {
        try {
            CTTbl ctTable = table.getCTTbl();
            CTTblPr tblPr = ctTable.getTblPr();
            if (tblPr == null) {
                tblPr = ctTable.addNewTblPr();
            }
            
            // 表格宽度
            CTTblWidth tblWidth = tblPr.addNewTblW();
            tblWidth.setType(STTblWidth.PCT);
            tblWidth.setW(BigInteger.valueOf(10000)); // 100%宽度
            
//            // 表格对齐
//            CTJc jc = tblPr.addNewJc();
//            jc.setVal(STJc.CENTER);
            
        } catch (Exception e) {
            System.err.println("设置表格样式时出错: " + e.getMessage());
        }
    }
    
    /**
     * 创建表头
     */
    private static void createTableHeader(XWPFTable table) {
        XWPFTableRow headerRow = table.createRow();
        
        String[] headers = {"序号", "工序名称", "副产品名称", "分配方法", "分配系数", "描述"};
        
        for (int i = 0; i < headers.length; i++) {
            XWPFTableCell cell = headerRow.getCell(i);
            if (cell == null) {
                cell = headerRow.createCell();
            }
            setCellContent(cell, headers[i], true, true);
        }
        
        // 设置表头样式
        setRowStyle(headerRow, "E6E6E6");
    }
    
    /**
     * 创建数据行
     */
    private static void createDataRows(XWPFTable table, List<AllocationData> dataList) {
        for (int i = 0; i < dataList.size(); i++) {
            AllocationData data = dataList.get(i);
            XWPFTableRow dataRow = table.createRow();
            
            // 填充数据
            setCellContent(dataRow.getCell(0), String.valueOf(i + 1), false, true);
            setCellContent(dataRow.getCell(1), data.getProcessName(), false, false);
            setCellContent(dataRow.getCell(2), data.getByProductName(), false, false);
            setCellContent(dataRow.getCell(3), data.getAllocationMethod(), false, false);
            setCellContent(dataRow.getCell(4), String.format("%.3f", data.getAllocationFactor()), false, true);
            setCellContent(dataRow.getCell(5), data.getDescription(), false, false);
            
            // 交替行背景色
            if (i % 2 == 0) {
                setRowStyle(dataRow, "F9F9F9");
            }
        }
    }
    
    /**
     * 设置单元格内容
     */
    private static void setCellContent(XWPFTableCell cell, String text, boolean isBold, boolean centerAlign) {
        if (cell == null) return;
        
        // 清空单元格
        for (int i = cell.getParagraphs().size() - 1; i >= 0; i--) {
            cell.removeParagraph(i);
        }
        
        // 创建新段落
        XWPFParagraph paragraph = cell.addParagraph();
        
        // 设置对齐
        if (centerAlign) {
            paragraph.setAlignment(ParagraphAlignment.CENTER);
        } else {
            paragraph.setAlignment(ParagraphAlignment.LEFT);
        }
        
        // 创建文本
        XWPFRun run = paragraph.createRun();
        run.setText(text != null ? text : "");
        run.setFontFamily("宋体");
        run.setFontSize(10);
        run.setBold(isBold);
        
        // 设置单元格属性
        cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.CENTER);
    }
    
    /**
     * 设置行样式
     */
    private static void setRowStyle(XWPFTableRow row, String backgroundColor) {
        for (XWPFTableCell cell : row.getTableCells()) {
            cell.setColor(backgroundColor);
        }
    }
    
    /**
     * 生成分配数据
     */
    private static List<AllocationData> generateAllocationData() {
        List<AllocationData> dataList = new ArrayList<>();
        
        dataList.add(new AllocationData("黏合剂生产", "废水", "物理分配法", 0.150, "基于质量比例分配"));
        dataList.add(new AllocationData("金属加工", "废金属", "经济价值法", 0.320, "基于市场价格分配"));
        dataList.add(new AllocationData("组件组装", "废包装", "系统扩展法", 0.100, "替代方法处理"));
        dataList.add(new AllocationData("原料处理", "粉尘", "物理分配法", 0.085, "基于排放量分配"));
        
        return dataList;
    }
    
    /**
     * 调试方法：列出所有表格内容
     */
    private static void listAllTablesContent(XWPFDocument doc) {
        System.out.println("=== 文档中所有表格内容 ===");
        int tableCount = 0;
        
        for (XWPFTable table : doc.getTables()) {
            tableCount++;
            System.out.println("表格 " + tableCount + ":");
            
            for (int i = 0; i < table.getNumberOfRows(); i++) {
                XWPFTableRow row = table.getRow(i);
                System.out.print("  行 " + (i+1) + ": ");
                
                for (XWPFTableCell cell : row.getTableCells()) {
                    String cellText = getCellText(cell).trim();
                    System.out.print("[" + cellText + "] ");
                }
                System.out.println();
            }
            System.out.println();
        }
        
        System.out.println("共找到 " + tableCount + " 个表格");
    }
    
    /**
     * 数据类
     */
    public static class AllocationData {
        private String processName;
        private String byProductName;
        private String allocationMethod;
        private double allocationFactor;
        private String description;
        
        public AllocationData(String processName, String byProductName, 
                             String allocationMethod, double allocationFactor, String description) {
            this.processName = processName;
            this.byProductName = byProductName;
            this.allocationMethod = allocationMethod;
            this.allocationFactor = allocationFactor;
            this.description = description;
        }
        
        public String getProcessName() { return processName; }
        public String getByProductName() { return byProductName; }
        public String getAllocationMethod() { return allocationMethod; }
        public double getAllocationFactor() { return allocationFactor; }
        public String getDescription() { return description; }
    }
}